package com.wdh.kjs.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.ListViewForScrollView;
import com.wdh.kjs.Adapter.MessageEditAdapter;
import com.wdh.kjs.Adapter.MessageListAdapter;
import com.wdh.kjs.MainActivity;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.DateUtils;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by chenqinhuang on 2016/4/21.
 */
public class MessageEditActivity extends BaseTopActivity implements View.OnClickListener {
    private Button bt_sme_allread;
    private Button bt_sme_delete;
    private MessageEditAdapter messageEditAdapter;
    private List<HashMap<String, String>> datas = new ArrayList<>();
    private HashMap<String, String> maps = new HashMap<String, String>();
    private PullToRefreshListView listview;
    private ScrollView scrollview;
    private JsonModel_my jsonModel_my;
    public static String  myId="";
    private String partyId;
    public static int page = 1;
    public static int rows = 7;
    protected LinearLayout ll_topBack;
    public static int totalrecords = 0;
    public  boolean mLoading = true;
    private String a="";
    private Intent intent;
    public static List<String> list=new ArrayList<>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_station_message_edit);
        initTopBar("消息详情");
        SharedPreferences share = getSharedPreferences("logininfo", MODE_PRIVATE);
        partyId = share.getString("loginToken", "");
        page = 1;
        initview();
//        initwidge();
        initweb();
    }

    private void initweb() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("partyId", partyId);
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_STSTION_MESSAGE, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                if (jsonModel_my.success) {
                    totalrecords = jsonModel_my.getTotalrecords();
                    Log.i("msg", "totalrecords_1 " + totalrecords);
                    initwidge();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(MessageEditActivity.this, "网络异常！");
            }
        });

    }

    private void initview() {
//        datas = (List<HashMap<String, String>>) this.getIntent().getSerializableExtra("list");
//        Log.i("msg", datas.size() + "  "+datas);

        listview = (PullToRefreshListView) findViewById(R.id.activity_message_edit_listview);
//        scrollview = (ScrollView) findViewById(R.id.activity_message_edit_scrollview);
//        scrollview.smoothScrollTo(0, 0);
        ll_topBack = (LinearLayout) findViewById(R.id.ll_topBack);
        bt_sme_allread = (Button) findViewById(R.id.bt_sme_allread);
        bt_sme_allread.setOnClickListener(this);
        bt_sme_delete = (Button) findViewById(R.id.bt_sme_delete);
        bt_sme_delete.setOnClickListener(this);
        ll_topBack.setOnClickListener(this);
    }
    private void initwidge() {
        messageEditAdapter = new MessageEditAdapter(this, initListViewData());
        listview.setAdapter(messageEditAdapter);
        listview.setMode(PullToRefreshBase.Mode.BOTH);
        listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            // 下拉Pulling Down
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时候数据重置
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();
            }

            // 上拉Pulling Up
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉的时候添加选项
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();
            }
        });
    }
    private class GetDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (totalrecords > datas.size()) {
                Log.i("msg","totalrecords_2 "+totalrecords+datas.size());
                page += 1;
                try {
                    getMoreList();
                } catch (Exception e) {
                    page -= 1;
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            if (mLoading == false)
                ToastUtils.showShort(MessageEditActivity.this, "已无更多数据！");
            listview.onRefreshComplete();

            super.onPostExecute(aVoid);

        }
    }

    private void getMoreList() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("partyId", partyId);
        params.addBodyParameter("page", page+"");
        params.addBodyParameter("rows", rows+"");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_STSTION_MESSAGE, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                if (jsonModel_my.success) {

                    Log.i("msg","totalrecords_3 "+jsonModel_my.getMessageList().size()+" "+jsonModel_my);

                    if (jsonModel_my != null&& jsonModel_my.getMessageList().size()> 0) {
                        moreListViewData();
                    } else{
                        page -= 1;
                        ToastUtils.showShort(MessageEditActivity.this, "没有更多数据！");
                    }
                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(MessageEditActivity.this, "网络异常！");
            }
        });
    }
    private List<HashMap<String, String>> initListViewData() {
        datas = new ArrayList<>();
        for (int i = 0; i < jsonModel_my.getMessageList().size(); i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            if(jsonModel_my.getMessageList().get(i).getUserMessageDel().equals("0")){
                hashMap.put("tv_message_title", jsonModel_my.getMessageList().get(i).getUserMessageTitle());
                hashMap.put("tv_message_time", jsonModel_my.getMessageList().get(i).getCreatedTxStamp().substring(0, 10));
                hashMap.put("userReceiveMessageId", jsonModel_my.getMessageList().get(i).getUserReceiveMessageId());
                hashMap.put("userMessageState", jsonModel_my.getMessageList().get(i).getUserMessageState());

                datas.add(hashMap);
            }
        }
        return datas;

    }
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_sme_delete:
                if (list.size()==0)
                    TipDialogShow("请先选择消息！");
                else {
               for (int i=0;i<list.size();i++)
                a = a + ","+list.get(i);
                a=a.substring(1,a.length());

                intweb();}
                break;
            case R.id.bt_sme_allread:
                if(list.size()==0){
                    TipDialogShow("请先选择消息！");
                }else {
                    for (int i=0;i<list.size();i++){
                        a = a + ","+list.get(i);
                        Log.i("ddd"," "+list.get(i)+"");
                    }
                    a=a.substring(1,a.length());
                    intDel();
                }
                break;

            case R.id.ll_topBack:
                intent = new Intent();
                intent.setClass(this, MyAccountTopTurnActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void intweb() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("messageidlist",a);

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_DELETE_MSG, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);


                if (jsonModel_my.success) {
                    list.clear();
                   startActivity(new Intent(MessageEditActivity.this,MessageEditActivity.class));
                }else
                    ToastUtils.showShort(MessageEditActivity.this, "删除失败！");
            }
            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(MessageEditActivity.this, "网络异常！");
            }
        });

    }

    private void intDel() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("messagereadlist",a);

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_READ_MSG, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);


                if (jsonModel_my.success) {
                    Log.i("msg","totalrecords_1 ");
                    list.clear();
                    startActivity(new Intent(MessageEditActivity.this,MessageEditActivity.class));
                }else
                    ToastUtils.showShort(MessageEditActivity.this, "删除失败！");
            }
            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(MessageEditActivity.this, "网络异常！");
            }
        });

    }

    private void moreListViewData() {
        for (int i = 0; i < jsonModel_my.getMessageList().size(); i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            if(jsonModel_my.getMessageList().get(i).getUserMessageDel().equals("0")){
                hashMap.put("tv_message_title", jsonModel_my.getMessageList().get(i).getUserMessageTitle());
                hashMap.put("tv_message_time", jsonModel_my.getMessageList().get(i).getCreatedTxStamp().substring(0,10));
                hashMap.put("userReceiveMessageId", jsonModel_my.getMessageList().get(i).getUserReceiveMessageId());
                hashMap.put("userMessageState", jsonModel_my.getMessageList().get(i).getUserMessageState());
                datas.add(hashMap);
            }
        }
        if (datas.size() == totalrecords)
            mLoading = false;
        messageEditAdapter.notifyDataSetChanged();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//这里重写返回键

            intent = new Intent();
            intent.setClass(this, MyAccountTopTurnActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
            startActivity(intent);

            return true;
        }
        return false;

    }

    private void TipDialogShow(String hint) {
        View dialog = View.inflate(this,R.layout.view_dialog_tip, null);
        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_false_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
    }
}
